<template>
  <el-cascader
    v-model="selectedRegion"
    :options="regionData"
    :props="props"
    :placeholder="placeholder"
    :clearable="clearable"
    :disabled="disabled"
    @change="handleChange"
  />
</template>

<script>
import { regionData } from '@/utils/region-data'

export default {
  name: 'RegionSelect',
  props: {
    // 省份值
    province: {
      type: String,
      default: ''
    },
    // 城市值
    city: {
      type: String,
      default: ''
    },
    // 占位符
    placeholder: {
      type: String,
      default: '请选择省市'
    },
    // 是否可清空
    clearable: {
      type: Boolean,
      default: true
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      regionData,
      selectedRegion: [],
      props: {
        value: 'value',
        label: 'label',
        children: 'children'
      }
    }
  },
  watch: {
    province: {
      handler(val) {
        this.initSelectedRegion()
      },
      immediate: true
    },
    city: {
      handler(val) {
        this.initSelectedRegion()
      },
      immediate: true
    }
  },
  methods: {
    // 初始化选中的省市
    initSelectedRegion() {
      if (this.province && this.city) {
        const province = this.regionData.find(item => item.label === this.province)
        if (province) {
          const city = province.children.find(item => item.label === this.city)
          if (city) {
            this.selectedRegion = [province.value, city.value]
          }
        }
      } else {
        this.selectedRegion = []
      }
    },
    // 处理选择变化
    handleChange(value) {
      if (value && value.length === 2) {
        const province = this.regionData.find(item => item.value === value[0])
        const city = province.children.find(item => item.value === value[1])
        this.$emit('update:province', province.label)
        this.$emit('update:city', city.label)
        this.$emit('change', { province: province.label, city: city.label })
      } else {
        this.$emit('update:province', '')
        this.$emit('update:city', '')
        this.$emit('change', { province: '', city: '' })
      }
    }
  }
}
</script> 